#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <gpiod.h>
#include <alsa/asoundlib.h>
#include <stdbool.h>
#include <signal.h>

#define KEY2_LINE 7  // 假设KEY2连接到GPIO10
#define KEY3_LINE 8  // 假设KEY3连接到GPIO11

// 全局变量
static bool keep_running = true;

// 信号处理函数
void signal_handler(int signum) {
    keep_running = false;
}

// 调整音量的函数
void adjust_volume(long volume_change) {
    long min, max;
    snd_mixer_t *handle;
    snd_mixer_selem_id_t *sid;
    const char *card = "default";
    const char *selem_name = "PCM";

    snd_mixer_open(&handle, 0);
    snd_mixer_attach(handle, card);
    snd_mixer_selem_register(handle, NULL, NULL);
    snd_mixer_load(handle);

    snd_mixer_selem_id_alloca(&sid);
    snd_mixer_selem_id_set_index(sid, 0);
    snd_mixer_selem_id_set_name(sid, selem_name);
    snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid);

    snd_mixer_selem_get_playback_volume_range(elem, &min, &max);
    long volume;
    snd_mixer_selem_get_playback_volume(elem, 0, &volume);

    volume += volume_change;
    if (volume < min) volume = min;
    if (volume > max) volume = max;

    snd_mixer_selem_set_playback_volume_all(elem, volume);

    snd_mixer_close(handle);
}

int main() {
    struct gpiod_chip *chip;
    struct gpiod_line *key2_line, *key3_line;
    int key2_value, key3_value;
    int last_key2_value = 1, last_key3_value = 1;  // 初始状态为高电平

    // 设置信号处理
    signal(SIGINT, signal_handler);

    // 打开GPIO芯片
    chip = gpiod_chip_open_by_label("GPIOF");  // 根据您的设备可能需要调整
    if (!chip) {
        perror("打开GPIO芯片失败");
        return 1;
    }

    // 获取GPIO线
    key2_line = gpiod_chip_get_line(chip, KEY2_LINE);
    key3_line = gpiod_chip_get_line(chip, KEY3_LINE);
    if (!key2_line || !key3_line) {
        perror("获取GPIO线失败");
        gpiod_chip_close(chip);
        return 1;
    }

    // 将GPIO线设置为输入模式
    if (gpiod_line_request_input(key2_line, "key2") < 0 ||
        gpiod_line_request_input(key3_line, "key3") < 0) {
        perror("请求将GPIO线设置为输入模式失败");
        gpiod_chip_close(chip);
        return 1;
    }

    printf("按键监控启动。按Ctrl+C退出。\n");

    // 主循环
    while (keep_running) {
        key2_value = gpiod_line_get_value(key2_line);
        key3_value = gpiod_line_get_value(key3_line);

        // 检测KEY2
        if (key2_value != last_key2_value && key2_value == 0) {
            printf("key2 pressed\n");
            adjust_volume(5);  // 增加音量
        }

        // 检测KEY3
        if (key3_value != last_key3_value && key3_value == 0) {
            printf("key3 pressed\n");
            adjust_volume(-5);  // 减小音量
        }

        last_key2_value = key2_value;
        last_key3_value = key3_value;

        usleep(50000);  // 50ms延迟，减少CPU使用
    }

    // 清理资源
    gpiod_line_release(key2_line);
    gpiod_line_release(key3_line);
    gpiod_chip_close(chip);

    printf("程序已终止\n");
    return 0;
}
